import tkinter as tk
import math


class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("计算器")
        self.expression = ""
        self.history = []  # 用于存储历史记录

        # 显示区域
        self.output = tk.Entry(root, font=('Arial', 25), borderwidth=5, relief='ridge')
        self.output.grid(row=0, column=0, columnspan=4)

        # 历史记录显示区域
        self.history_box = tk.Text(root, height=10, width=30, state='disabled', font=('Arial', 12))
        self.history_box.grid(row=5, column=0, columnspan=4)
        # 按钮布局
        self.create_buttons()

    def create_buttons(self):
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', 'C', '=', '+',
            'x²', '√', 'log', '^',
            '历史记录'
        ]

        row_val = 1
        col_val = 0
        for button in buttons:
            self.create_button(button, row_val, col_val)
            col_val += 1
            if col_val > 3:
                col_val = 0
                row_val += 1

    def create_button(self, text, row, column):
        button = tk.Button(self.root, text=text, padx=20, pady=20, font=('Arial', 18),
                           command=lambda: self.on_button_click(text))
        button.grid(row=row, column=column)

    def on_button_click(self, char):
        if char == 'C':
            self.expression = ""
            self.output.delete(0, tk.END)
        elif char == '=':
            try:
                result = eval(self.expression)
                self.output.delete(0, tk.END)
                self.output.insert(0, str(result))
                self.history.append(f"{self.expression} = {result}")  # 添加历史记录
                self.expression = str(result)
            except Exception as e:
                self.output.delete(0, tk.END)
                self.output.insert(0, "错误")
                self.expression = ""
        elif char in ['x²', '√', 'log', '^']:
            if self.expression:
                if char == 'x²':
                    self.expression = str(float(self.expression) ** 2)
                elif char == '√':
                    self.expression = str(math.sqrt(float(self.expression)))
                elif char == 'log':
                    self.expression = str(math.log(float(self.expression)))  # 计算自然对数
                elif char == '^':
                    self.output.delete(0, tk.END)
                    self.output.insert(0, f"{self.expression} ^ ")
                    self.expression += '**'  # 将输入的表达式准备为指数操作
                self.output.delete(0, tk.END)
                self.output.insert(0, self.expression)
        elif char == '历史记录':
            self.show_history()  # 显示历史记录
        else:
            self.expression += str(char)
            self.output.delete(0, tk.END)
            self.output.insert(0, self.expression)

    def show_history(self):
        self.history_box.config(state='normal')  # 允许编辑历史记录框
        self.history_box.delete('1.0', tk.END)  # 清空历史记录框
        for entry in self.history:
            self.history_box.insert(tk.END, entry + '\n')  # 插入历史记录条目
        self.history_box.config(state='disabled')  # 重新设置为只读状态


if __name__ == "__main__":
    root = tk.Tk()
    calculator = Calculator(root)
    root.mainloop()